package com.example.listener;

import com.alibaba.fastjson.JSON;
import com.example.entity.Order;
import com.example.enums.MsgEnum;
import com.example.enums.OrderStatusEnum;
import com.example.mapper.OrderMapper;
import com.example.msg.api.MsgApi;
import com.example.msg.dto.MsgDTO;
import com.example.order.dto.OrderDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues = "msg_queue")
public class MsgHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(MsgHandler.class);
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private MsgApi msgApi;

    @RabbitHandler
    public void process(String content){
        LOGGER.info("接收到支付信息:"+content);
        //对应设计图  第8步骤.处理本地业务
        OrderDTO orderDTO= JSON.parseObject(content, OrderDTO.class);
        Order order=new Order();
        order.setOrderNo(orderDTO.getOrderNo());
        Order obj=this.orderMapper.selectOne(order);
        obj.setStatus(OrderStatusEnum.PAY_SUCCESS.getCode());
        this.orderMapper.updateByPrimaryKeySelective(obj);

        //最后删除消息，对应设计图，第9步骤将消息直接删除
        String msgid= MsgEnum.ORDER.getCode()+"-"+orderDTO.getOrderNo();
        MsgDTO msgDTO=new MsgDTO();
        msgDTO.setMsgId(msgid);
        this.msgApi.deleteMsg(msgDTO);
    }
}
